# In some cases, the semantic version string is not defined. Try to find it.
if(NOT DEFINED P4C_SEM_VERSION_STRING)
  # Semantic version numbering: <major>.<minor>.<patch>[-rcX]
  # Examples: 0.5.1, 1.0.0-rc1, 1.0.1-alpha
  execute_process(
    COMMAND cat ${P4C_SOURCE_DIR}/Version.txt
    OUTPUT_VARIABLE P4C_SEM_VERSION_STRING
    OUTPUT_STRIP_TRAILING_WHITESPACE
    RESULT_VARIABLE rc
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
  )
  string(
    REGEX MATCH "([0-9]+)\\.([0-9]+)\\.([0-9]+)([-0-9a-z\\.]*).*"
    __p4c_version ${P4C_SEM_VERSION_STRING}
  )
  set(P4C_VERSION_MAJOR ${CMAKE_MATCH_1})
  set(P4C_VERSION_MINOR ${CMAKE_MATCH_2})
  set(P4C_VERSION_PATCH ${CMAKE_MATCH_3})
  set(P4C_VERSION_RC ${CMAKE_MATCH_4})
  execute_process(
    COMMAND git rev-parse --short HEAD
    OUTPUT_VARIABLE P4C_GIT_SHA
    OUTPUT_STRIP_TRAILING_WHITESPACE
    RESULT_VARIABLE rc
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
  )
  set(P4C_VERSION "${P4C_SEM_VERSION_STRING} (SHA: ${P4C_GIT_SHA} BUILD: ${CMAKE_BUILD_TYPE})")
endif()

# CMake file for P4 tools.
project(P4TOOLS VERSION ${P4C_SEM_VERSION_STRING})

# Store the current git commit hash as part of version information.
execute_process(
  COMMAND git log --pretty=format:-%h -n 1
  OUTPUT_VARIABLE P4TOOLS_VERSION_HASH
  ERROR_QUIET
)

if(NOT "${P4TOOLS_VERSION_HASH}" STREQUAL "")
  message(STATUS "Current git refpoint: ${P4TOOLS_VERSION_HASH}")
endif()

# Add cmake directory to our module path. Also add cmake directory from p4c to
# inherit FindLibGc.
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

# Import common definitions.
include(common)

# For files generated by the protobuf compiler
include_directories(BEFORE ${P4C_BINARY_DIR}/control-plane)

enable_testing()
set(ENABLE_TESTING ON)

# Include sub projects.
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/common)

# Custom IR constructs for P4Tools.
set(IR_DEF_FILES ${IR_DEF_FILES} ${CMAKE_CURRENT_SOURCE_DIR}/p4tools.def)

file(GLOB tools_modules RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/modules ${CMAKE_CURRENT_SOURCE_DIR}/modules/*)
foreach(ext ${tools_modules})
  set(tools_dir ${CMAKE_CURRENT_SOURCE_DIR}/modules/${ext})
  if(EXISTS ${tools_dir}/CMakeLists.txt AND IS_DIRECTORY ${tools_dir})
    # Generate an option that makes it possible to disable this extension.
    string(MAKE_C_IDENTIFIER ${ext} EXT_AS_IDENTIFIER)
    string(TOUPPER ${EXT_AS_IDENTIFIER} EXT_AS_OPTION_NAME)
    string(CONCAT ENABLE_EXT_OPTION "ENABLE_TOOLS_MODULE_" ${EXT_AS_OPTION_NAME})
    string(CONCAT EXT_HELP_TEXT "Build the " ${ext} " module")
    option(${ENABLE_EXT_OPTION} ${EXT_HELP_TEXT} ON)
    if(${ENABLE_EXT_OPTION})
      message("-- Enabling P4Tools module ${ext}")
      add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/modules/${ext})
    endif()
  endif()
endforeach(ext)

# Propagate new def files upwards after all modules have been included.
set(IR_DEF_FILES ${IR_DEF_FILES} PARENT_SCOPE)
